<?php

namespace app\api\controller;
use Throwable;
use think\facade\Config;
use app\common\library\JwtUtil;
use app\common\controller\Api;
use app\admin\model\Admin;
use app\admin\model\User;
use app\api\validate\Admin as AdminValidate;
use EasyWeChat\MiniApp\Application;
use EasyWeChat\Pay\Application as payApp;
class Login extends Api
{
    protected array $noNeedLogin = ['index', 'logout'];

    public function initialize(): void
    {
        parent::initialize();
    }
    /**
     * 市场管理员登录
     * author：mozi
     * time:2025.05.16
     * */
    public function index(): void
    {   
         
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post(['username', 'password']);
            
            $validate = new AdminValidate();
            try {
                $validate->scene("login")->check($params);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }
            
            $find = Admin::where("username",$params['username'])->find();
            if($find){
                    if(!verify_password($params['password'], $find->password, ['salt' => $find->salt])) {
                        $this->error('账号或密码错误');
                    }
                    if(in_array(7,$find['group_arr'])){
                          $auth = 'agent';
                    }
                    if(in_array(6,$find['group_arr'])){
                          $auth = 'dealer';
                    }
                    if(in_array(8,$find['group_arr'])){
                          $auth = 'distributor';
                    }
                    // 2. 生成 Token
                    $token = $find->access_token;
                    $this->success("ok",['token'=>$token,'auth'=>$auth ??'']);    

            }else{
                  $this->error("账号或密码错误");
            }

             
 
        }

        
    }
    

    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }

    //静默登录
    function wxlogin(){
            
            $params = $this->request->post(['code']);
            $code = $params['code'] ?? '';
            if($code){
                    

                    try {
                        // 创建微信小程序对象
                        $wechat = new Application($this->getConfig());
                        // 获取 session_key 和 openid
                        $result = $wechat->getUtils()->codeToSession($code);
                        if(isset($result['openid'])){
                              $openid = $result['openid'];
                              $ip = $this->request->ip();
                              $find =  User::where("wx_openid",$openid)->field("id,wx_name,mobile,create_time")->find();
                              if($find){
                                   $r = User::where("wx_openid",$openid)->update(['last_login_time'=>time()]);
                              }else{
                                   $m = new User();
                                   $r = $m->save([
                                        'wx_name'=>'用户_'.rand(1000000,9999999),
                                        'wx_openid'=>$openid,
                                        'join_ip'=>$ip,
                                        'create_time'=>time(),
                                        'update_time'=>time(),
                                        'status'=>'enable'
                                   ]);
                                   $userId = $m->id;
                                   $find = User::where("id",$userId)->field("id,wx_name,mobile,create_time")->find();
                              } 

                              if($r){
                                   $token = JwtUtil::generateToken($find['id']);
                                   return json(['code'=>200,'msg'=>'ok','userinfo'=>$find,'token'=>$token??'']); 
                              }
                        }else{
                              return json(['code'=>100,'msg'=>'请重试']);
                        }


                    } catch (Throwable $e) {
                         $this->error($e->getMessage());
                    }
                    

            }else{
                  return json(['code'=>100,'msg'=>'code lost!']);
            }
            
    }

    
    public function vget($url) {
        $info = curl_init();
        curl_setopt($info, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($info, CURLOPT_HEADER, 0);
        curl_setopt($info, CURLOPT_NOBODY, 0);
        curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info, CURLOPT_URL, $url);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }

}